<template>
  <div class="container">
    <div class="wrapper">
      <mu-paper :z-depth="5">
        <form action="">
          <div class="login-input">
            <mu-text-field
              label="帐号"
              labelFloat
              full-width
              help-text="用户名为您的身份证号"
              v-model="account.userid"
            />
            <br />
            <mu-text-field
              label="密码"
              labelFloat
              full-width
              v-model="account.userpw"
              :action-icon="visibility ? 'visibility_off' : 'visibility'"
              :action-click="() => (visibility = !visibility)"
              :type="visibility ? 'text' : 'password'"
            />
            <br />
          </div>
          <div class="login-btn">
            <mu-flex justify-content="center" align-items="center">
              <mu-button full-width color="lightGreen500" @click.native="handleLoginClick">登录</mu-button>
            </mu-flex>
          </div>
        </form>
      </mu-paper>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { mapMutations } from 'vuex'
import { getItem, setItem } from '../../utils/localStorage'
const option = {
  durtaion: 1000
}
export default {
  name: 'Login',
  data () {
    return {
      account: {
        userid: getItem('userid') || '',
        userpw: getItem('password') || ''
      },
      visibility: false
    }
  },
  methods: {
    handleLoginClick () {
      let param = new URLSearchParams()
      param.append('userid', this.account.userid)
      param.append('password', this.account.userpw)
      if (this.account.userid && this.account.userpw) {
        axios.post('/api/login.do', param)
          .then(this.handleLoginSucc)
      } else {
        this.$toast('用户名密码不能为空', option)
      }
    },
    handleLoginSucc (res) {
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.login(data.token)
        setItem('userid', data.userid)
        setItem('password', data.password)
        let redirect = decodeURIComponent(this.$route.query.redirect || '/')
        this.$router.push({
          path: redirect
        })
      } else {
        this.$toast('用户名或密码错误', option)
      }
    },
    ...mapMutations([
      'login'
    ])
  }
}
</script>

<style lang="stylus" scoped>
  .container >>> .mu-switch-label
      color: rgba(0, 0, 0, .6)
  .container
    position: absolute
    display: flex
    flex-direction: column
    justify-content: flex-end
    left: 0
    top: 0
    right: 0
    bottom: 0
    background-image: url('../../assets/img/login-bg.jpg')
    background-size: 100% auto
    background-position: center center
    height: 100vh
    .mu-input
      margin-bottom: .2rem
      font-size: .36rem
    .wrapper
      overflow: hidden
      text-align: center
      height: 55vh
      padding: 0 .18rem
      .mu-paper
        padding: .42rem
      .login-btn
        margin-top: .5rem
</style>
